<template>


  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="昵称">
      <el-input v-model="form.nickname" disabled/>
    </el-form-item>

    <el-form-item label="头像">
      <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="uploadSuccess"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
        <el-icon v-else class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
      </el-upload>
    </el-form-item>

  </el-form>


</template>

<script setup>
import {ref} from 'vue'
import {updateAvatar} from '@/api/profile'
import {ElNotification} from "element-plus";
import {useUserStore} from "@/stores/userStore.js";

const userStore = useUserStore();


const form = ref({
  nickname: '系统管理员'
})

const api_url = import.meta.env.VITE_API_SERVER

const uploadUrl = `${api_url}/upload`
const imageUrl = ref()

if (userStore.getUserInfo?.avatar) {
  imageUrl.value = `${api_url}/downlod/${userStore.getUserInfo?.avatar}`
}


//上传成功
async function uploadSuccess(response, uploadFile, uploadFiles) {
  const {id} = response;
  imageUrl.value = `${api_url}/downlod/${id}`

  //更新用户表

  const success = await updateAvatar(id);
  if (success) {
    ElNotification({
      title: '消息',
      type: 'success',
      message: "更新头像成功",
    })
  } else {
    ElNotification({
      title: '消息',
      type: 'error',
      message: "更新头像失败",
    })
  }
}


</script>


<style scoped>
.avatar {
  max-height: 400px;
  max-width: 400px;
}
</style>